<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Product;


class ProductController extends Controller
{
    
    public function index(Request $request)
    {
        $param = [];
        $query = Product::query();
        if($request->keyword) {
            $param['keyword'] = trim($request->keyword);
            $query->where('name','like','%'.$request->keyword.'%');
        }
        $list  = $query->paginate(20);
       
        return view('admin.product.index',compact('list','param'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
       
        return view('admin.product.add');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = $request->except('_token');
        if ($request->file('pic')) {
            $data['pic'] = '/'.$request->pic->store('public/'.date('Ymd'));  
            $data['pic'] = str_replace('public', 'storage', $data['pic']);   
        }
        
        $rs   = Product::create($data);
        if($rs) {
            return redirect('zadmin/product');
        }
        return back();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = Product::find($id);
       
        return view('admin.product.edit',compact('data'));
    }

   
    public function update(Request $request, $id)
    {
        $data = $request->except('_token','_method');
        if ($request->file('pic')) {
            $data['pic'] = '/'.$request->pic->store('public/'.date('Ymd'));  
            $data['pic'] = str_replace('public', 'storage', $data['pic']);   
        }
        
        $rs   = Product::where('id',$id)->update($data);
        if($rs) {
            return redirect('zadmin/product');
        }
        return back()->withInput();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $rs = Product::destroy($id);
        if ($rs) {
            return redirect('zadmin/product');
        }
        return back();
    }

   
}
